package app.server.project.core.life;

import app.server.project.core.constants.CfgDef;
import jakarta.annotation.PreDestroy;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


@Component
@Data
@Slf4j
public class AppLifeMgr {

    /**
     * 死循环任务，比如数据库同步
     */
    public static List<IDeadLoopTask> LoopTasks = new ArrayList<>();
    /**
     * 程序退出时候,处理一些清理任务
     */
    public static List<ICommonTask> CommonTasks = new ArrayList<>();

    @Value("${" + CfgDef.APP + CfgDef.Wait_Time + ":60}")
    private long waitTime;


    @PreDestroy
    public void doDestroy() throws InterruptedException {
        log.info("开始退出系统");
        //开启独立的线程不断执行死循环任务
        new Thread(() -> {
            log.info("开始执行死循环任务");
            while (true) {
                LoopTasks.forEach(v -> {
                    v.doDeadLoopBeforeExitApp();
                });
            }
        }).start();
        log.info("开始执行普通退出任务");
        CommonTasks.forEach(v -> {
            v.doCommonTaskBeforeExitApp();
        });
        Thread.sleep(waitTime * 1000);
        log.info("系统成功关闭");
    }
}
